package com.czxy.controller;

import com.aliyuncs.exceptions.ClientException;
import com.czxy.pojo.User;
import com.czxy.service.UserService;
import com.czxy.util.GetRandomCodeUtil;
import com.czxy.util.SmsUtil;
import com.czxy.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author 张青卯
 */
@RestController
@RequestMapping
public class UserController {

    private final RedisTemplate<String,String> redisTemplate;

    private final UserService userService;

    @Autowired
   public UserController(UserService userService, RedisTemplate<String, String> redisTemplate){
       this.userService = userService;
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/regist")
    public ResponseEntity<BaseResult> regist(@RequestBody User user){
        String yzm = redisTemplate.opsForValue().get(user.getMobile());
        assert yzm != null;
        if (yzm.equals(user.getCode())){
            userService.saveUser(user);
        }
        BaseResult result = new BaseResult(0,"成功",null);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/sms")
    public ResponseEntity<BaseResult> sms(@RequestBody User user){
        String s = redisTemplate.opsForValue().get(user.getMobile());
        assert s != null;
        if (!("".equals(s))){
            BaseResult br = new BaseResult(0, "验证码已发送，请注意查收", null);
            return ResponseEntity.ok(br);
        }
        User user1 = userService.selectOne(user);
        if (user1 == null){
            try {
                String code = GetRandomCodeUtil.getCode();
                redisTemplate.opsForValue().set(user.getMobile(),code,60*5, TimeUnit.SECONDS);
                SmsUtil.sendSms(user.getMobile(),"验证码有效时间为五分钟"+code);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        BaseResult result = new BaseResult(0,"成功",null);
        return ResponseEntity.ok(result);
    }

    /**
     * findUserByMobile 远程调用 登录
     * @param mobile 手机号
     * @param password 密码
     * @return user
     */
    @GetMapping("query")
    ResponseEntity<User> findUserByMobile(@RequestParam String mobile,@RequestParam String password){
        User user = userService.findUserByMobileAndPassword(mobile, password);
        return ResponseEntity.ok(user);
    }

}
